package com.xinchao.ck_mips.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.Toast;

import com.xinchao.ck_mips.contract.BaseContract;
import com.xinchao.rxtools.rxhttp.tools.IDisposable;
import com.xinchao.rxtools.rxhttp.tools.RxSubscriber;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class BaseActivity extends AppCompatActivity implements IDisposable, BaseContract.View {

    private CompositeDisposable compositeDisposable = new CompositeDisposable();
    private Toast mToast;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
                WindowManager.LayoutParams. FLAG_FULLSCREEN);
        setContentView(getLayoutId());
        onCreated(savedInstanceState);
    }

    protected abstract int getLayoutId();

    protected abstract void onCreated(Bundle savedInstanceState);

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeAllDisposable();
        compositeDisposable = null;
    }

    @Override
    public void showToast(String msg) {
        if (mToast != null) {
            mToast.cancel();
        }

        mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
        mToast.show();
    }

    @Override
    public void showToastOnUiThread(String msg) {
        Flowable.just(msg).observeOn(AndroidSchedulers.mainThread()).subscribe(new RxSubscriber<String>(getDisposable()) {
            @Override
            protected void next(String s) {
                showToast(s);
            }
        });
    }

    @Override
    public void showToast(int msg) {
        showToast(getString(msg));
    }

    @Override
    public void showToastOnUiThread(int msg) {
        showToastOnUiThread(getString(msg));
    }

    @Override
    public BaseActivity getBaseActivity() {
        return this;
    }

    @Override
    public IDisposable getDisposable() {
        return this;
    }

    @Override
    public void addDisposable(Disposable disposable) {
        if (disposable == null || compositeDisposable == null) {
            return;
        }
        compositeDisposable.add(disposable);
    }

    @Override
    public void removeDisposable(Disposable disposable) {
        if (disposable == null || compositeDisposable == null) {
            return;
        }
        compositeDisposable.remove(disposable);
    }


    @Override
    public String formatString(int resId, Object... params) {
        return getString(resId, params);
    }

    @Override
    public void removeAllDisposable() {
        compositeDisposable.clear();
    }
}
